package com.niuwa.p2p.action.quartz;

import java.io.File;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.quartz.CronScheduleBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.niuwa.p2p.action.JsonAction;
import com.niuwa.p2p.core.constant.FileSystemEnum;
import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.entity.job.JobEntity;
import com.niuwa.p2p.service.filesystem.FileSystem;
import com.niuwa.p2p.service.job.JobService;
import com.niuwa.p2p.utils.schedule.SchedulerHelper;
import com.niuwa.p2p.vo.job.JobVo;
import com.opensymphony.xwork2.ModelDriven;

import javax.servlet.http.HttpServletRequest;

@Namespace("/quartz")
@Controller
public class QuartzAction extends JsonAction implements ModelDriven<Object> {

	@Autowired
	private JobService jobService;

//	@Autowired
//	private SchedulerHelper schedulerHelper;

	private JobEntity jobEntity;

	public JobEntity getJobEntity() {
		return jobEntity;
	}

	public void setJobEntity(JobEntity jobEntity) {
		this.jobEntity = jobEntity;
	}

	public final static String DATE_FORMAT_LONG = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 
	 */
	private static final long serialVersionUID = -6062567199020635959L;

	@Action("index")
	public String index() {
		return "index";
	}

	/**
	 * 任务列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "taskList")
	public String taskList() throws Exception {
		setObjectReSult(queryPagination());
		return NONE;
	}

	/**
	 * 任务列表分页查询
	 * 
	 * @return
	 */
	private PageBean<JobVo> queryPagination() {
		// 获取查询参数
		Map<String, Object> paramMap = getParamMap();
		// 任务名称
		if (!StringUtil.isEmpty((String) paramMap.get("jobName"))) {
			paramMap.put((String) paramMap.get("jobName"),
					paramMap.get("jobName"));
		}
		// 任务分组
		if (!"-1".equals(paramMap.get("jobGroup"))
				&& paramMap.get("jobGroup") != null) {
			paramMap.put("jobGroup", paramMap.get("jobGroup"));
		}
		// 任务状态
		if (!"-1".equals(paramMap.get("jobStatus"))
				&& paramMap.get("jobStatus") != null) {
			paramMap.put("jobStatus", paramMap.get("jobStatus"));
		}
		// 执行查询操作
		PageBean<JobVo> pagination = jobService.selectJobs(paramMap);
		return pagination;
	}

	/**
	 * 增加任务
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("gotoAddJobPage")
	public String gotoAddJobPage() throws Exception {
		return "addJobPage";
	}

	/**
	 * 角色新增
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addJob")
	public String addJob() throws Exception {
		JsonResult results = new JsonResult();
		HttpServletRequest req = getRequest();
		jobEntity.setJobName(req.getParameter("jobName"));
		jobEntity.setDescription(req.getParameter("description"));
		jobEntity.setJobGroup(Integer.valueOf(req.getParameter("jobGroup")));
		jobEntity.setCronExpression(req.getParameter("cronExpression"));
		jobEntity.setSpringId(req.getParameter("springId"));
		jobEntity.setJobMethod(req.getParameter("jobMethod"));
		jobEntity.setJobStatus(JobEntity.STATUS_INIT);
		jobEntity.setRunDuration(0L);
		jobEntity.setExceptionTimes(0L);
		jobEntity.setRunTimes(0L);
		if (Integer.valueOf(req.getParameter("jobGroup")).equals("2")) {
			jobEntity.setSyncBeginTime(DateUtil.parseStringToDate(
					req.getParameter("syncBeginTime"), DATE_FORMAT_LONG));
			jobEntity.setSyncEndTime(DateUtil.parseStringToDate(
					req.getParameter("syncEndTime"), DATE_FORMAT_LONG));
		}
		try {
			jobService.saveJob(jobEntity);
			results.setMsg("新增成功");
			setResult(results);
		} catch (Exception ex) {
			ex.printStackTrace();
			results.setMsg("新增失败");
			setResult(results);
			ex.printStackTrace();
		}
		return NONE;
	}

	/**
	 * 任务修改
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "updateJob")
	public String updateJob() throws Exception {
		JsonResult results = new JsonResult();
		HttpServletRequest req = getRequest();
		Long jobId = Long.valueOf(req.getParameter("jobId"));
		String oldGroupName = null;
		try {
			JobEntity job = jobService.getJobById(jobId);
			oldGroupName = String.valueOf(job.getJobGroup());
			job.setJobName(req.getParameter("jobName"));
			job.setJobGroup(Integer.valueOf(req.getParameter("jobGroup")));
			job.setCronExpression(req.getParameter("cronExpression"));
			job.setSpringId(req.getParameter("springId"));
			job.setJobMethod(req.getParameter("jobMethod"));
			job.setDescription(req.getParameter("description"));
			if (Integer.valueOf(req.getParameter("jobGroup")).equals("2")) {
				job.setSyncBeginTime(DateUtil.parseStringToDate(
						req.getParameter("syncBeginTime"), DATE_FORMAT_LONG));
				job.setSyncEndTime(DateUtil.parseStringToDate(
						req.getParameter("syncEndTime"), DATE_FORMAT_LONG));
			}
			jobService.updateJob(job);
			// 更新下任务调度服务
//			schedulerHelper.getScheduler(); // 获取初始化scheduler对象
//			schedulerHelper.removeJob(jobId, oldGroupName);
			results.setMsg("修改成功");
			setResult(results);
		} catch (Exception e) {
			results.setMsg("修改失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;

	}

	/**
	 * 跳转角色修改页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "gotoUpdateJobPage")
	public String gotoUpdateRolePage() throws Exception {
		HttpServletRequest req = getRequest();
		Long jobId = Long.valueOf(req.getParameter("jobId"));
		jobEntity = jobService.getJobById(jobId);
		jobEntity.setSyncBeginTimeStr(DateUtil.formatDateToString(
				jobEntity.getSyncBeginTime(), DATE_FORMAT_LONG));
		jobEntity.setSyncEndimeStr(DateUtil.formatDateToString(
				jobEntity.getSyncEndTime(), DATE_FORMAT_LONG));
		return "updateJobPage";
	}

	@Action(value = "openJob")
	public String openJob() throws Exception {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			Long jobId = Long.valueOf(req.getParameter("jobId"));
			jobEntity = jobService.getJobById(jobId);
			jobEntity.setJobStatus(JobEntity.STATUS_OPENED);
			jobService.updateJob(jobEntity);
			results.setMsg("开启成功");
			setResult(results);
		} catch (Exception e) {
			results.setMsg("开启失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;
	}

	@Action(value = "closeJob")
	public String closeJob() throws Exception {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			Long jobId = Long.valueOf(req.getParameter("jobId"));
			jobEntity = jobService.getJobById(jobId);
			jobEntity.setJobStatus(JobEntity.STATUS_INIT);
			jobService.updateJob(jobEntity);
			results.setMsg("关闭成功");
			setResult(results);
			// 更新下任务调度服务
//			schedulerHelper.getScheduler(); // 获取初始化scheduler对象
//			schedulerHelper.removeJob(jobId,
//					String.valueOf(jobEntity.getJobGroup()));
		} catch (Exception e) {
			results.setMsg("关闭失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;
	}

	@Action(value = "delJob")
	public String delJob() throws Exception {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			Long jobId = Long.valueOf(req.getParameter("jobId"));
			jobEntity = jobService.getJobById(jobId);
			jobService.delJob(jobEntity);
			results.setMsg("删除成功");
			setResult(results);
			// 更新下任务调度服务
//			schedulerHelper.getScheduler(); // 获取初始化scheduler对象
//			schedulerHelper.removeJob(jobId,
//					String.valueOf(jobEntity.getJobGroup()));
		} catch (Exception e) {
			results.setMsg("删除失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;
	}

	@Action(value = "runJob")
	public String runJob() throws Exception {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			Long jobId = Long.valueOf(req.getParameter("jobId"));
			jobEntity = jobService.getJobById(jobId);
			// 更新下任务调度服务
//			schedulerHelper.getScheduler(); // 获取初始化scheduler对象
//			schedulerHelper.executeOneceJob(jobId,
//					String.valueOf(jobEntity.getJobGroup()));
			results.setMsg("执行成功");
			setResult(results);
		} catch (Exception e) {
			results.setMsg("执行失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;
	}

	@Action(value = "pauseJob")
	public String pauseJob() throws Exception {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			Long jobId = Long.valueOf(req.getParameter("jobId"));
			jobEntity = jobService.getJobById(jobId);
			// 更新下任务调度服务
//			schedulerHelper.getScheduler(); // 获取初始化scheduler对象
//			schedulerHelper.pauseJob(jobId,
//					String.valueOf(jobEntity.getJobGroup()));
			results.setMsg("暂停成功");
			jobEntity.setJobStatus(jobEntity.STATUS_PAUSE);
			jobService.updateJob(jobEntity);
			setResult(results);
		} catch (Exception e) {
			results.setMsg("暂停失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;
	}

	@Action(value = "resumeJob")
	public String resumeJob() throws Exception {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			Long jobId = Long.valueOf(req.getParameter("jobId"));
			jobEntity = jobService.getJobById(jobId);
			// 更新下任务调度服务
//			schedulerHelper.getScheduler(); // 获取初始化scheduler对象
//			schedulerHelper.resumeJob(jobId,
//					String.valueOf(jobEntity.getJobGroup()));
			results.setMsg("恢复成功");
			jobEntity.setJobStatus(jobEntity.STATUS_WAIT);
			jobService.updateJob(jobEntity);
			setResult(results);
		} catch (Exception e) {
			results.setMsg("恢复失败");
			setResult(results);
			e.printStackTrace();
		}
		return NONE;
	}

	@Action(value = "cronExpression")
	public String cronExpression() {
		JsonResult results = new JsonResult();
		try {
			HttpServletRequest req = getRequest();
			CronScheduleBuilder
					.cronSchedule(req.getParameter("cronExpression"));
			results.setMsg("true");
			setResult(results);
		} catch (Exception e) {
			results.setMsg("false");
			setResult(results);
		}
		return NONE;
	}

	@Override
	public Object getModel() {
		if (jobEntity == null) {
			jobEntity = new JobEntity();
		}
		return jobEntity;
	}

}
